package com.mtiiot.fsmanage.server;


import com.mtiiot.fsmanage.bean.common.Column;
import com.mtiiot.fsmanage.bean.common.SysTreeNode;
import com.mtiiot.fsmanage.bean.common.TableDataInfo;
import com.mtiiot.fsmanage.utils.TimeUtil;
import com.mtiiot.fscore.utils.StringUtil;
import com.mtiiot.fsmanage.core.dao.BaseElasticsearch;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class EsServer {
    @Autowired
    private BaseElasticsearch baseElasticsearch;

    public Object getRootNode() throws Exception{
        List<SysTreeNode> list=new ArrayList<SysTreeNode>();
        SysTreeNode st=new SysTreeNode();
        st.setId("1");
        st.setText("索引");
        st.setChildren(true);
        list.add(st);
        return list;
    }
    public Object getChildrenNode(String id,String index) throws Exception {
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            SearchResponse sr=null;
            List<Terms.Bucket> list=null;
            List<SysTreeNode> sts=new ArrayList<SysTreeNode>();
            boolean hasChildren=true;
            if(id.equals("1")){
                //////////////////////查询索引////////////////
                sr = client.prepareSearch("index*")
                        .addAggregation(
                                AggregationBuilders.terms("agg1").field("_index").size(20)
                        ).execute().actionGet();

            }else if(id.split("-").length==2){
                //////////////////////查询类型////////////////
                hasChildren=false;
                sr = client.prepareSearch(index)
                        .addAggregation(
                                AggregationBuilders.terms("agg1").field("_type").size(100)
                        ).execute().actionGet();
            }
            Terms agg1 = sr.getAggregations().get("agg1");
            list=agg1.getBuckets();
            int i=1;
            Object key=null;
            String text=null;
            for(Terms.Bucket b:list){
                SysTreeNode st=new SysTreeNode();
                st.setId(id+"-"+i);
                key=b.getKey();
                text=key.toString();
                st.setText(text);
                st.setChildren(hasChildren);
                sts.add(st);
                i++;
            }
            return sts;
        }finally {
            if(client!=null){
                baseElasticsearch.getEsDataSource().releaseClient(client);
            }
        }
    }


    public Object esQuery(String index,String type,String times,String queryKeyWord,int count,String sort) throws Exception {
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            BoolQueryBuilder bq=QueryBuilders.boolQuery();
            if(!StringUtil.isEmpty(queryKeyWord)){
                bq.must(QueryBuilders.queryStringQuery(queryKeyWord));
            }
            long[] l= TimeUtil.handleTimes(times);
            if(l!=null&&l.length>0){
               bq.must(QueryBuilders.rangeQuery("time").from(l[0]).to(l[1]));
            }
            QueryBuilder queryBuilder = bq;
            if(StringUtil.isEmpty(index)){
                index="index*";
            }
            SearchRequestBuilder srb=null;
            SortOrder sortOrder=null;
            if("desc".equals(sort)){
                sortOrder=SortOrder.DESC;
            }else{
                sortOrder=SortOrder.ASC;
            }
            if(StringUtil.isEmpty(type)){
                srb = client.prepareSearch(index).setFrom(0)
                        // 设置查询结果集的最大条数
                        .setSize(count)
                                // 设置是否按查询匹配度排序
                        .setExplain(true)
                                //按时间降序号
                        .addSort("time", sortOrder);
                       // .setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
            }else{
                srb = client.prepareSearch(index)
                        .setTypes(type).setFrom(0)
                                // 设置查询结果集的最大条数
                        .setSize(count)
                                // 设置是否按查询匹配度排序
                        .setExplain(true)
                                //按时间降序号
                        .addSort("time",sortOrder);
                        //.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
            }

            srb.setQuery(bq);

            TableDataInfo tdif=new TableDataInfo();
            SearchResponse response =srb.execute().actionGet();
            SearchHits searchHits = response.getHits();
            tdif.setCount(searchHits.totalHits());
            SearchHit[] hits = searchHits.getHits();

            List<Map<String, Object>> sms=new ArrayList<Map<String, Object>>();
            List<Column> columns=new ArrayList<Column>();
            Set<String> set=null;
            for (SearchHit searchHit : hits) {
                Map<String, Object> sm = searchHit.sourceAsMap();
                sms.add(sm);
                if(set==null){
                    set=sm.keySet();
                }
            }
            if(set!=null){
                Column column=null;
                for(String key:set){
                    column=new Column();
                    column.setField(key);
                    column.setTitle(key);
                    columns.add(column);
                }
            }
            tdif.setColumns(columns);
            tdif.setObject(sms);
            return tdif;
        }finally {
            if(client!=null){
                baseElasticsearch.getEsDataSource().releaseClient(client);
            }
        }
    }
}
